﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.IO;
using System.Drawing;
using System.Web.UI.HtmlControls;
using System.Web.Security;

public partial class admin_UserDetail : SitePage
{
    #region Fields
    busUserProfile _busUserProfile = new busUserProfile();
    public string Command
    {

        get
        {
            object o = ViewState["Command"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["Command"] = value; }

    }
    public Guid UserID
    {

        get
        {
            object o = ViewState["UserID"];
            if (o != null) return new Guid(o.ToString());
            return Guid.Empty;
        }

        set { ViewState["UserID"] = value; }

    }
    #endregion

    #region Init,Load
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        InitData();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadRoleData();
            LoadData();
        }
    }
    #endregion

    #region Methods
    private void LoadRoleData()
    {
        busaspnet_Roles objBusRole = new busaspnet_Roles();
        int maxLevel = objBusRole.GetMaxRoleLevel(this.ApplicationName, this.userloginId);
        string[] role = Roles.GetAllRoles();
        foreach (string itemRole in role)
        {
            aspnet_Roles objRole = objBusRole.GetByName(this.ApplicationName, itemRole);
            if (objRole != null && objRole.Level <= maxLevel)
                cblRole.Items.Add(new ListItem(itemRole, itemRole));
        }
    }
    private void LoadData()
    {
        if (this.Command == "edit")
        {
            MembershipUser user = Membership.GetUser(this.UserID);
            if (user != null)
            {
                UserProfile profile = _busUserProfile.GetByID(this.UserID);
                if (profile != null)
                {
                    txtFirstName.Text = profile.FirstName;
                    txtLastname.Text = profile.LastName;
                    txtUserCode.Text = profile.UserCode;
                    if (profile.IsAllowLogin)
                    {
                        trUserName.Visible = true;
                        if (this.Command != "edit")
                        {
                            trPass.Visible = true;
                            trConfirmPass.Visible = true;
                        }
                        else
                        {
                            trPass.Visible = false;
                            trConfirmPass.Visible = false;
                        }
                        chkIsAllowLogin.Checked = true;
                    }
                    else
                    {
                        trUserName.Visible = false;
                        trPass.Visible = false;
                        trConfirmPass.Visible = false;
                        chkIsAllowLogin.Checked = false;
                    }
                }
                else {
                    trUserName.Visible = true;
                    if (this.Command != "edit")
                    {
                        trPass.Visible = true;
                        trConfirmPass.Visible = true;
                    }
                    else
                    {
                        trPass.Visible = false;
                        trConfirmPass.Visible = false;
                    }
                    chkIsAllowLogin.Checked = true;
                }
                txtEmail.Text = user.Email;
                txtUserName.Text = user.UserName;
                txtUserName.Enabled = false;
                string[] role = Roles.GetRolesForUser(user.UserName);
                for (int i = 0; i < cblRole.Items.Count; i++)
                {
                    if (RoleExists(cblRole.Items[i].Value, role))
                        cblRole.Items[i].Selected = true;
                }
                if (user.IsApproved)
                    chkIsActive.Checked = true;
                else chkIsActive.Checked = false;
            }
        }
    }
    private bool RoleExists(string value, string[] source)
    {
        foreach (string role in source)
        {
            if (role.Trim() == value.Trim())
                return true;
        }
        return false;
    }
    private void InitData()
    {
        string validateGroup = "user";
        vsumUser.ValidationGroup = cusUserName.ValidationGroup = reqRole.ValidationGroup = btnSave.ValidationGroup = reqFirstName.ValidationGroup = reqLastName.ValidationGroup = reqConfirmPass.ValidationGroup = reqEmail.ValidationGroup = reqPass.ValidationGroup = cmpConfirmPass.ValidationGroup = regvEmail.ValidationGroup = reqUsername.ValidationGroup = validateGroup;
        //Init message
        reqFirstName.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "First name");
        reqLastName.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Last name");
        reqEmail.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Email");
        reqUsername.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "User name");
        reqUserCode.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "User Code");
        reqPass.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Password");
        reqRole.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Role");
        reqConfirmPass.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Confirm password");
        regvEmail.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Email");
        cusUserName.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "User name");
        cmpConfirmPass.ErrorMessage = string.Format(Resources.Resource.MSG_COMPARE, "Confirm password", "Password");
        this.Command = clsQueryString.GetString("act");
        try
        {
            this.UserID = new Guid(clsQueryString.GetString("id"));
        }
        catch
        {
            this.Command = "";
        }
        if (this.Command == "edit")
        {
            reqConfirmPass.Enabled = false;
            reqPass.Enabled = false;
            cmpConfirmPass.Enabled = false;
        }
    }
    private void InsertUser(UserProfile profile, string userName,string password)
    {
        try
        {
            MembershipUser user = Membership.CreateUser(userName.Trim(), password.Trim(), txtEmail.Text.Trim());
            if (user != null)
            {
                if (!chkIsActive.Checked)
                {
                    user.IsApproved = false;
                    Membership.UpdateUser(user);
                }
                //ProfileCommon profile = this.Profile.GetProfile(user.UserName);
                //profile.FirstName = txtFirstName.Text.Trim();
                //profile.LastName = txtLastname.Text.Trim();
                //profile.Save();
                //Add roles
                foreach (ListItem item in cblRole.Items)
                {
                    if (item.Selected)
                    {
                        Roles.AddUserToRole(userName, item.Text);
                    }
                }
                profile.UserId =new Guid(user.ProviderUserKey.ToString());
                //save profile
                _busUserProfile.Insert(profile);
                Response.Redirect("UserList.aspx");

            }
            else
                lblErrorMessage.Text = Resources.Resource.MSG_INSERT_ERROR;
        }
        catch (MembershipCreateUserException ex)
        {
            switch (ex.StatusCode)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    {
                        lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "User name");
                        break;
                    }
                case MembershipCreateStatus.DuplicateEmail:
                    {
                        lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "Email");
                        break;
                    }
                case MembershipCreateStatus.InvalidEmail:
                    {
                        lblErrorMessage.Text = string.Format(Resources.Resource.MSG_VALID, "Email");
                        break;
                    }
                case MembershipCreateStatus.InvalidPassword:
                    {
                        lblErrorMessage.Text = string.Format(Resources.Resource.MSG_VALID, "Password");
                        break;
                    }
                case MembershipCreateStatus.InvalidUserName:
                    {
                        lblErrorMessage.Text = string.Format(Resources.Resource.MSG_VALID, "Username");
                        break;
                    }
            }
        }

    }
    private void UpdateUser(UserProfile profile, string userName, string password)
    {
        try
        {
            MembershipUser user = Membership.GetUser(userName);
            //check email is exist
            string userNameCheck = Membership.GetUserNameByEmail(txtEmail.Text);
            if (userNameCheck != null && !userNameCheck.Equals(userName))
            {
                lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "Email");//Email is exist
                return;
            }
            user.Email = txtEmail.Text;
            if (chkIsActive.Checked)
                user.IsApproved = true;
            else user.IsApproved = false;
            //edit roles
            string[] roles = Roles.GetRolesForUser(txtUserName.Text);
            try
            {
                Roles.RemoveUserFromRoles(txtUserName.Text, roles);
            }
            catch
            { }
            //Add roles
            foreach (ListItem item in cblRole.Items)
            {

                if (item.Selected)
                {
                    try
                    {
                        Roles.AddUserToRole(txtUserName.Text, item.Text);
                    }
                    catch
                    { }
                }
            }
            Membership.UpdateUser(user);
            //ProfileCommon profile = this.Profile.GetProfile(user.UserName);
            //profile.FirstName = txtFirstName.Text;
            //profile.LastName = txtLastname.Text;
            //profile.Save();
            profile.UserId = new Guid(user.ProviderUserKey.ToString());
            
            _busUserProfile.Update(profile);
            Response.Redirect("UserList.aspx");

        }
        catch (MembershipCreateUserException e)
        {
            lblErrorMessage.Text = Resources.Resource.MSG_UPDATE_ERROR;
        }
    }
    #endregion

    #region Events, Handle
    protected void chkIsAllowLogin_CheckedChanged(object sender, EventArgs e)
    {
        if (chkIsAllowLogin.Checked)
        {
            trUserName.Visible = true;

            if (this.Command != "edit")
            {
                trPass.Visible = true;
                trConfirmPass.Visible = true;
            }
            else
            {
                trPass.Visible = false;
                trConfirmPass.Visible = false;
            }
        }
        else
        {
            trUserName.Visible = false;
            trPass.Visible = false;
            trConfirmPass.Visible = false;
        }

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //getData
            UserProfile objProfile = new UserProfile();
            objProfile.FirstName = txtFirstName.Text.Trim();
            objProfile.LastName = txtLastname.Text.Trim();
            if (chkIsAllowLogin.Checked)
                objProfile.IsAllowLogin = true;
            else objProfile.IsAllowLogin = false;
            objProfile.UserCode = txtUserCode.Text.Trim();
            objProfile.CreatedBy = this.userloginName;
            objProfile.CreatedDate = clsDateTime.Now;
            objProfile.ModifiedBy = this.userloginName;
            objProfile.ModifiedDate = clsDateTime.Now;
            //check user code exists
            clsSQL sql = new clsSQL();
            string sqlCheck = string.Empty;
            if (this.Command == "edit")
                sqlCheck = "Select count(*) from UserProfile where UserCode='" + objProfile.UserCode + "' and UserId<>'" + this.UserID.ToString() + "'";
            else
                sqlCheck = "Select count(*) from UserProfile where UserCode='" + objProfile.UserCode + "'";
            int count = (int)sql.ExecuteScalar(sqlCheck);
            if (count > 0)
            {
                lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "User Code");
                return;
            }
            string userName = string.Empty;
            string pass = string.Empty;
            if (!objProfile.IsAllowLogin)
            {
                userName = objProfile.UserCode;
                pass = objProfile.UserCode + "123456";
            }
            else
            {
                userName = txtUserName.Text.Trim();
                pass = txtPass.Text.Trim();
            }
            if (this.Command == "edit")
                UpdateUser(objProfile,userName,pass);
            else InsertUser(objProfile, userName, pass);
        }
        else
        {
            vsumUser.ShowMessageBox = false;
            vsumUser.ShowSummary = true;
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("UserList.aspx");
    }
    #endregion

    #region Validate Data
    protected void CheckSUserNameValid(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsValidate.CheckUserNameValid(args.Value);
    }

    #endregion

}